package org.timeticker.gui;

import org.apache.log4j.Logger;

import java.lang.reflect.Method;

/**
 * Bean helper class
 *
 * @author Ivan Latysh
 * @version 0.1
 * @since 11-Aug-2007 : 6:11:43 PM
 */
public class BeanHelper {

  /** Component logger */
  protected static Logger logger = Logger.getLogger(BeanHelper.class.getName());

  /**
   * Get bean property via reflection
   *
   * @param bean bean
   * @param property property name
   * @return property value or null
   */
  public static Object getPropertyValue(Object bean, String property) {
    if (null==bean || null==property) throw new IllegalArgumentException("Bean or property is null {bean="+bean+"; property="+property+"}");
    // construct accessor method name
    String propertyAccessor = "get" + property.substring(0,1).toUpperCase() + property.substring(1,property.length());
    try {
      // look for the property accessor method
      Method method = bean.getClass().getMethod(propertyAccessor, null);
      return method.invoke(bean, null);
    } catch (NoSuchMethodException e) {
      logger.error("[OLTM00001] Method {"+propertyAccessor+"} does not exist in class {"+bean.getClass().getName()+"}", e);
    } catch (Exception e) {
      logger.error("[OLTM00002] Error when tyring to read property {"+propertyAccessor+"} from bean {"+bean+"}", e);
    }
    return null;
  }

}
